<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				label-width="100px"
				class="flex-warp-container"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					class="flex-row-container">
					<merchant-select
						v-model="queryData.merchantId"
						v-symbols
						:placeholder="$t('common.all')"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('agent.total_agent_account')}:`"
					class="flex-row-container">
					<el-input
						v-model="queryData.proxyUsername"
						v-input="{ name: 'symbols' }"
						clearable
						:maxlength="11"
						size="medium"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.business_model')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.businessModel"
						size="medium"
						:placeholder="$t('common.all')"
						style="width: 200px"
						clearable
					>
						<el-option
							v-for="item in businessModelList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('909360443')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="actionAdd()"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<ReportDetailTable
				:tableDataColumn="tableDataColumn"
				:tableDataList="tableData"
				:tableLoading="loading"
				:tableHeight="tableHeight"
			>
				<template v-slot:actionSlot="{ rowData, index }">
					<el-link
						v-if="hasPermission('909360444')"
						type="primary"
						@click="actionEdit(rowData)"
						>
						{{ $t('common.edit') }}
					</el-link>
					<el-link
						v-if="hasPermission('909360445') && rowData.proxyId !== 0"
						type="primary"
						@click="actionDelete(rowData)"
						>
						{{ $t('common.delete') }}
					</el-link>
				</template>
			</ReportDetailTable>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<!--新增编辑-->
		<el-dialog
			:title="titleText"
			:visible.sync="addEditDailog"
			:close-on-click-modal="false"
			:destroy-on-close="true"
			width="620px"
			center
		>
			<el-form
				ref="formSubAuto"
				:model="dialogForm"
				label-width="auto"
				:rules="rules"
			>
				<el-form-item
					v-if="dialogForm.proxyId !== 0"
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="dialogForm.merchantId"
						:placeholder="$t('common.please_choose')"
						:merchantInfo.sync="merchantInfo"
						style="width: 330px"
					></merchant-select>
				</el-form-item>
				<el-form-item
					v-if="dialogForm.proxyId !== 0"
					:label="`${$t('agent.total_agent_account')}:`"
					prop="proxyUsername"
				>
					<el-input
						v-model="dialogForm.proxyUsername"
						type="text"
						style="width: 330px"
						:placeholder="$t('common.please_enter')"
						:maxlength="11"
						v-input="{ name: 'symbols' }"
					></el-input>
				</el-form-item>
				<el-form-item
					v-if="dialogForm.proxyId !== 0"
					:label="`${$t('common.business_model')}:`"
					prop="businessModel"
				>
					<el-select
						v-model="dialogForm.businessModel"
						size="medium"
						:placeholder="$t('common.please_choose')"
						style="width: 330px"
						:disabled="true"
						clearable
					>
						<el-option
							v-for="item in businessModelList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>

				<el-form-item
					:label="`${$t('operation.login_state_vaid_time')}:`"
					prop="loginValidTime"
				>
					<el-input
						v-model="dialogForm.loginValidTime"
						type="text"
						style="width: 330px"
						:maxlength="10"
						v-input="{name: 'int'}"
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addEditDailog = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.confirm') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import dayjs from 'dayjs'
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'
import { getColumns } from './components/columns'
import { POS_INT_PATTERN } from '@/utils/pattern'
export default {
	name: routerNames.agentAutoLoginOutConfig,
	components: {
		MainContent,
		ReportDetailTable: () => import('@/components/ReportDetailTable')
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {
			},
			tableData: [],
			tableDataColumn: [],
			total: 0,
			rowVal: {},
			addEditDailog: false,
			titleText: '',
			merchantInfo: {},
			dialogForm: {
				merchantId: undefined,
				proxyUsername: undefined,
				businessModel: undefined,
				loginValidTime: undefined,
				proxyId: undefined,
				merchantName: undefined
			}
		}
	},
	computed: {
		businessModelList(){
			return this.globalDics.businessModelTypeArr || []
		},
		rules() {
			const checkTopProxyName = (rule, value, callback) => {
				const params = {
					userName: this.dialogForm.proxyUsername
				}
				this.$api
					.checkProxyDetailAPI(params)
					.then((res) => {
						this.loading = false
						const { data } = res
						if (data.length === 0) {
							callback(this.$t('operation.proxy_account_no'))
						} else {
							if (data[0]?.proxyLevel === 0) {
								this.dialogForm.businessModel = data[0]?.businessModel
								this.dialogForm.proxyId = data[0]?.id
								callback()
							} else {
								callback(this.$t('operation.proxy_account_no'))
							}
						}
					})
					.catch(() => {
						this.loading = false
					})
			}
			const checkLoginStateTime = (rule, value, callback) => {
				if (!value) {
					callback(this.$t('common.please_enter'))
				} else if (value == 0) {
					this.dialogForm.loginValidTime = value?.replace('0','')
				} else if(value < 10) {
					callback(this.$t('operation.please_enter_10_tips'))
				} else if(!(POS_INT_PATTERN.test(value))) {
					callback(this.$t('operation.activity_list.integer'))
				} else {
					callback()
				}
			}
			return {
				merchantId: [
					{
						required: true,
						message: this.$t(
							'common.please_choose'
						),
						trigger: ['blur']
					}
				],
				proxyUsername: [
					{
						required: true,
						message: this.$t(
							'common.please_enter'
						),
						trigger: ['blur']
					},
					{
						required: true,
						validator: checkTopProxyName,
						trigger: ['blur']
					}
				],
				businessModel: [
					{
						required: true,
						message: this.$t('common.please_choose'),
						trigger: ['blur']
					}
				],
				loginValidTime: [
					{
						required: true,
						validator: checkLoginStateTime,
						trigger: ['blur']
					}
				]
			}
		}
	},
	created() {
	},
	mounted() {
		this.tableDataColumn = getColumns()
	},
	methods: {
		//新增
		actionAdd() {
			this.addEditDailog = true
			this.titleText = this.$t('common.add')
			if (!this.$store.getters.isZk) {
				this.dialogForm = {
					merchantId: undefined,
					proxyUsername: undefined,
					businessModel: undefined,
					loginValidTime: undefined,
					proxyId: undefined,
					merchantName: undefined
				}
			} else {
				this.dialogForm = {
					merchantId: undefined,
					proxyUsername: undefined,
					businessModel: undefined,
					loginValidTime: undefined,
					proxyId: undefined,
					merchantName: undefined
				}
			}
		},
		//编辑
		actionEdit(rowVal) {
			this.titleText = this.$t('common.edit')
			this.dialogForm = { ...rowVal }
			this.$set(this.dialogForm,'proxyId',rowVal.proxyId)
			this.addEditDailog = true
		},
		//删除弹框
		actionDelete(rowVal) {
			this.$confirm(`<strong>是否删除该条配置?</strong><br><strong style='color:#999'>请谨慎操作</strong>`, `确认提示`, {
				dangerouslyUseHTMLString: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'positionIcon'
			})
				.then(() => {
					this.$api.proxyLoginOutDeleteAPI({id: rowVal.proxyId}).then((res) => {
						if (res.code === 200) {
							this.$message.success('删除成功')
							this.loadData()
						}
					})
				})
				.catch(() => {})
		},
		subAddOrEdit() {
			const params = {
				...this.dialogForm

			}
			params.loginValidTime = +this.dialogForm.loginValidTime
			if (this.titleText == this.$t('common.add')) {
				params.merchantName = this.merchantInfo.merchantName
			}
			const handleClick =
				this.titleText == this.$t('common.edit')
					? this.$api.proxyLoginOutEditAPI
					: this.$api.proxyLoginOutAddAPI
			this.$refs.formSubAuto.validate((valid) => {
				if (valid) {
					handleClick(params).then((res) => {
						const { code, msg } = res
						if (code === 200) {
							this.$message({
								message: `${
									this.titleText !== this.$t('common.edit')
										? this.$t('common.add_success')
										: this.$t('common.edit_success')
								}`,
								type: 'success'
							})
							this.loadData()
						} else {
							this.$message({
								message: msg,
								type: 'error'
							})
						}
					})
					this.addEditDailog = false
				}
			})
		},
		loadData() {
			this.loading = true
			let params = {
				...this.queryData,
				...this.getParams()
			}
			this.tableData = []
			let _self = this
			this.$api
				.getProxyLoginOutConfigList(params)
				.then((res) => {
					_self.loading = false
					const {
						code,
						data: { record, totalRecord },
						msg
					} = res
					if (code === 200) {

						_self.tableData = Array.isArray(record)
							? Object.freeze(record)
							: []
						_self.total = totalRecord || 0
					} else {
						this.loading = false
						this.$message({
							message: msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					_self.loading = false
				})
		},
		reset() {
			this.queryData = {}
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped></style>
